﻿using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;

namespace Fetches.Fetch.Utils.KvStore
{
    /// <summary>
    ///     我知道redis更好用，但是单机测试的时候不想依赖redis服务器的状态
    ///     不要优化这个KvStore，没必要,redis服务器没事的话鬼才想用这个KvStore
    /// </summary>
    public class DictKvStore : IKvStore
    {
        private ConcurrentDictionary<string, string> _dictionary
            = new ConcurrentDictionary<string, string>();


        private string _persistenceFile;

        public void Initialize(string config, long uniqueId)
        {
            _persistenceFile = Path.Combine(config, uniqueId.ToString());
            Directory.CreateDirectory(Path.GetDirectoryName(_persistenceFile));
            if (File.Exists(_persistenceFile))
            {
                var lines = File.ReadAllLines(_persistenceFile);
                foreach (var line in lines)
                {
                    var kvPair = JsonConvert.DeserializeObject<KeyValuePair<string, string>>(line);
                    _dictionary.AddOrUpdate(kvPair.Key, kvPair.Value, (currentKey, currentValue) => kvPair.Value);
                }
            }

        }

        public bool Exists(string key)
        {
            return _dictionary.ContainsKey(key);
        }

        public void Put(string key, string value)
        {
            _dictionary.AddOrUpdate(key, value, (currentKey, currentValue) => value);
            var line = JsonConvert.SerializeObject(new KeyValuePair<string, string>(key, value));
            lock (this)
            {
                File.AppendAllLines(_persistenceFile, new[] { line });
            }

        }

        public string Get(string key)
        {
            if (_dictionary.TryGetValue(key, out var value))
            {
                return value;
            }

            return string.Empty;
        }

        public void Dispose()
        {
        }
    }
}